<script type="text/javascript">
	console.log($("#task_detail_form").form().length);
	if ($("#task_detail_form").form().length > 1) {
		console.log("帮助easyui删除隐藏的element");
		$("#task_popwin").remove();
		$("#task_popwin_buttons").remove();
		
	}
</script>

<!-- datagrid部分 -->
<table id="task_list"></table>

<!-- 条件查询、按钮 -->
<form  id="task_search">
	<table>
		<tr>
		    
			<td>
				标题：<input name="title" class="easyui-textbox"   data-options="prompt:'标题'"  style="width:120px" />
			<td>
				正文:<input name="content" class="easyui-textbox" data-options="prompt:'正文'"  style="width:120px"  />
			</td>
				<td>状态:</td>
				<td><select  id="task_status"  name="status" class="easyui-combobox"      style="width:200px;">
				   <option value="0">未完成</option>
                   <option value="1">已完成</option>
                    </select> </td>
            <td>
			 <input type="checkbox" id="own"  name="own"  class="easyui-checkbox"  ><label>只显示本部门任务</label>
			 </td>
			<td>
			 <input type="checkbox" id="rigor"  name="rigor" checked="checked"   style="display: none"  > <!-- <label>模糊查询</label>   -->
				<a href="#" plain="true" id="task_search_submit" onclick="javascript:;">查询</a>
				<a href="#" plain="true" id="task_search_reset" onclick="javascript:;">重置</a>
			</td>
		</tr>
	</table>
	
	<div style="padding-top:2px;"></div>
	
	<a href="#" id="task_add" onclick="javascript:;">添加</a>
    <a href="#" id="task_edit" onclick="javascript:;">修改</a>
    <a href="#" id="task_del" onclick="javascript:;">删除</a>
	<!-- <a href="#"  id="task_export"    onclick="javascript:;">数据导出</a> -->
</form>

<!-- 弹出窗口 detail -->
<div id="task_popwin" class="easyui-dialog"
	style="width: 750px; height: 680px; padding: 10px 30px;"
	title="新建工作任务" buttons="#task_popwin_buttons"
	data-options="modal:true,closed:true">
	 <h3><label>工作任务信息</label></h3>
     <form id="task_detail_form" class="easyui-form" method="post">
     <input type="text" name="id"  id="task_id" style="width: 30px; display: none" />
		<table>
			<tr>
				<td>标题</td>
				<td><input  id="title" name="title"  
					style="width: 540px;"  class="easyui-textbox"
					data-options="validType:'length[1,200]',required:true"  /></td></tr>
			<tr>
				<td>正文:</td>
				<td><input   id="content"  name="content"    class="easyui-textbox"  data-options="multiline:true,validType:'length[1,3000]'"
					style="width: 540px;height:200px;border: 1px solid #95B8E7;-webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;"  ></input> </td> <td id="buchongTd" style="display: none">   <a href="#" id="buchongBtn" onclick="javascript:;"  >补充</a></td>
			</tr>
			<tr  id="buchongTr"  style="display: none"  >
				<td>补充内容</td>
				<td><input   id="buchong"  name="buchong"  class="easyui-textbox"  data-options="multiline:true,validType:'length[1,500]'"
					style="width: 540px;height:60px;border: 1px solid #95B8E7;-webkit-border-radius: 5px 5px 5px 5px;
            border-radius: 5px 5px 5px 5px;"  ></input> </td>
			</tr>
			<tr>
				<td>附件</td><td><input  id="attachments"   name="attachments"  
					style="width: 540px;height:30px" class="easyui-tagbox" data-options="
						editable:false,
						multiple:true,
                		textField: 'text',
						limitToList:true,
		    			hasDownArrow:false,
						data: [ ]"  /></td> <td>   <a href="#" id="task_import" onclick="javascript:;">上传</a></td></tr>
			 
			<tr>
				<td>办限时间:</td>
				<td><input     id="endDate"
					style="width: 540px;"  class="easyui-datebox"/></td></tr>
			
			<tr>
				<td>所属部门:</td>
				<td><select id="dept" class="easyui-combotree"  data-options="required:true,multiple: true"
					url="api/user/getL1DeptSubList" name="deptIds"  style="width: 540px;"  ></select></td>
			</tr>
				<tr>
				<td>责任人:</td>
				<td><select id="doerCodes" class="easyui-combobox" data-options="
						valueField:'code',
                		textField:'name',
						limitToList:true,
						multiple: true,
		    			hasDownArrow:true"
					 name="doerCodes" style="width: 540px;"  ></select></td>
			</tr>
			<tr>
				<td>备注:</td> 
				<td><input  id="remark" name="remark" style="width: 540px;" id="remark" 
					class="easyui-textbox" /></td>
				 
			</tr>
			 <input type="text" name="jgId"  id="all_pbc" style="width: 30px; display: none" />
				<!-- <td><select id="all_pbc" class="easyui-combotree"
					url="api/getallpbc" name="jgId" style="width: 540px;" disabled="disabled"></select></td> -->
			 
			<tr>
				<td>完成状态:</td>
				<td><input  name="status"   id="status" class="easyui-combobox"   data-options="
						valueField: 'id',
    					textField: 'text',
						editable:false,
						limitToList:true,
		    			hasDownArrow:true,
						data: [{'id':'0','text':'未完成'},{'id':'1','text':'已完成'}
						]" style="width:540px;" /></td>
			</tr>
			

		</table>
     </form>
</div>
<div id="task_popwin_buttons">
	<a href="#" id="task_save" onclick="javascript:;">提交保存</a>
</div>

<!-- 弹出窗口 uploadExcel -->
<div id="task_import_popwin" class="easyui-dialog"
	style="width: 400px; height: 200px; padding: 10px 30px;"
	title="文件上传" buttons="#task_import_buttons"
	data-options="modal:true,closed:true">
	<form id="task_import_form" method="post" enctype="multipart/form-data">
		<table  style="width:98%;border-collapse:separate;border-spacing:10px;">
			<tr>
				<td>
					<input id="task_import_file" name="upload_file" class="easyui-filebox" 
						style="width: 90%" data-options="
						buttonText:'选择文件'"/>
				</td>
			</tr>
		</table>
	</form>
</div>
<div id="task_import_buttons">
    <a href="#" id="task_import_button" onclick="javascript:;">文件上传</a>
</div>

<script type="text/javascript">
var  task_search= function(){
	var state="";
	var modelname="Task";
	var pageName="task";
   	var listPage=$("#"+pageName+"_list");
   	var search_form=pageName+"_search"
   	var submit_button=$("#"+pageName+"_search_submit");
   	var reset_button=$("#"+pageName+"_search_reset");
	var export_button=$("#"+pageName+"_export");
   	var popupWin=$("#"+pageName+"_popwin");
  //以下根据id获取按钮元素
	var query_button=$("#"+pageName+"_query");
	var add_button=$("#"+pageName+"_add");
	var edit_button=$("#"+pageName+"_edit");
	var del_button=$("#"+pageName+"_del");
	var import_button=$("#"+pageName+"_import");
	var save_button=$("#"+pageName+"_save");
  	//文件上传弹窗
   	var importWin=$("#"+pageName+"_import_popwin");
   	var importForm=$("#"+pageName+"_import_form");
   	var importFile=$("#"+pageName+"_import_file");
   	var importButton=$("#"+pageName+"_import_button");
	//编辑弹窗
	var detailForm=$("#"+pageName+"_detail_form");
   	var popupWin=$("#"+pageName+"_popwin");
   	
   	var columnsAll = new Array();  
    
	        listPage.datagrid({
	            url: 'api/'+modelname+'/search',
	            singleSelect: true,
	            pagination: true,
	            fitColumns:true,
				nowrap:false,
	            rownumbers:true,
	            toolbar:"#"+search_form,
	            pageSize: 15,
	            pageList: [5, 10, 15, 20, 30, 50, 80, 200],
	            queryParams: form2Json(search_form),　　//关键之处
	            columns:[[{
		            field: "id",
		            title: "编号",
		            hidden: true
		        },{
		            field: "title",
		            title: "标题",
		            align: 'center',
		            width: 100
		        }, 
		        {
		            field: "content",
		            title: "正文",
		            align: 'center',
		            width: 180,
		            formatter: function(value, row) {
		                var abValue =encodeHtml(value);;
		                if (abValue.length>140) {
		                    abValue =abValue.substring(0,140)+"...";
		                }
		                return abValue;
		            }
		             
		        }
		        , 
		        {
		            field: "deptNames",
		            title: "责任部门",
		            align: 'center',
		            width: 60
		        } , 
		        {
		            field: "doerNames",
		            title: "责任人",
		            align: 'center',
		            width: 60
		        } , 
		        {
		            field: "endDate",
		            title: "办限日期",
		            align: 'center',
		            width: 40,
		            formatter: function(value, row) {
		            	if(row.endDate!=undefined)
		            	return moment(row.endDate).format("YYYY-MM-DD");
		            	else
		            	return ""
		            }
		            
		        } , 
		        {
		            field: "status",
		            title: "任务状态",
		            align: 'center',
		            width: 30,
		            formatter: function(value, row) {
		                var abValue ='未完成';
		                if (value==='1') {
		                    abValue ='已完成';
		                }
		                return abValue;
		            }
		             
		        }, 
		        {
		            field: "attachments",
		            title: "附件",
		            align: 'center',
		            width: 100
		            
		        }]], 
	            
	    		onDblClickRow:function(index,row){
	    			loadDetail();
	    			
	    		},
	    		rowStyler:function(value,row,index){
	    			if(row.deptNames!=undefined)
	    			if(row.deptNames.indexOf($.op.deptName)>-1){
	    			return 'background-color: ;color:#DB7093;';
	    			}
	    		}
		        }); 
             //#E6E6FA;
  submit_button.linkbutton({ iconCls: 'icon-search', plain: true })
    .click(function () {
    	var data=form2Json(search_form);
    	if($("#own").prop("checked"))
    		data.deptNames=$.op.deptName;
        listPage.datagrid({ queryParams:data});   //点击搜索
    });
  reset_button.linkbutton({ iconCls: 'icon-clear', plain: true })
  .click(function () {
	  $(':input','#'+search_form)  
      .not(':button, :submit, :reset')  
      .val(' ')  
      .removeAttr('checked')  
      .removeAttr('selected');

  });   
//新增，初始化detail窗口后打开
  add_button.linkbutton({ iconCls: 'icon-add', plain: true })
  .click(function () {
  	addNewone();
  });
  
	//等同于双击datagrid中的row
  edit_button.linkbutton({ iconCls: 'icon-edit', plain: true })
  .click(function () {
  	loadDetail();
  });
  
	//删除一条记录
  del_button.linkbutton({ iconCls: 'icon-cut', plain: true })
  .click(function () {
  	var row = listPage.datagrid('getSelected');
		if (row){
			$.messager.confirm('系统提示','确认要删除么?',function(r){
			    if (r){
			        $.get('api/'+modelname+'/del',{id:row.id},function(data){
			        	var data = JSON.parse(data);
			        	$.messager.alert("系统提示",data.msg);
			        	listPage.datagrid("reload");					        	
			        });
			    }
			});		
		}else{
			$.messager.alert("系统提示","请鼠标点击选择要删除的行！");
			return;
		}
  });
	//个性化编辑————————————保存数据，关闭detail窗口，刷新datagrid
  save_button.linkbutton({ iconCls: 'icon-ok', plain: true })
  .click(function () {
       save();
  });
  function addNewone(){
	 state="add";
	 $("#buchongTr").css("display","none");
	 $("#buchongTd").css("display","none");
  	//去掉datagrid中的选择row
  	listPage.datagrid('clearSelections');	
  	targetId=0;
  	//在弹出窗口画出各填充要素
  	//drawDetailElems();
  	//EasyUI渲染html元素
  	detailForm.form('reset');
    $("#attachments").tagbox('readonly',false);
  	$("#title").textbox('textbox').attr('readonly',true);
	$("#content").textbox('textbox').attr('readonly',true);
	/* $(':input','#task_detail_form')  
	.not(':button, :submit, :reset')  
	.removeAttr('readonly'); */
		$.parser.parse(detailForm);
		//弹出窗口初始化当前日期
		//$("#"+pageName+"_"+"updateDate").datebox('setText',moment().format("YYYY-MM-DD"));
		//弹出
	 $("#status").combobox('setValue','0');
	 popupWin.dialog({title: "新建工作任务"}).dialog('open');  
  }
  
  

	function save(){
		 var isValid =detailForm.form('validate');
	       if(!isValid){
	    	   $.messager.alert("提示","表单校验位通过，请检查输入项");
	           return false;
	       }

		detailForm.form('submit',{
			url:'api/'+modelname+'/save',
			onSubmit:function(param){
				/* $.each(columnsAll,function(index,element){
			      if (element["type"]=="easyui-datebox")
			          { 
			            var temp= $("#"+pageName+"_"+element["field"]).datebox('getText').toString().split('-');	
			      		param[element["field"]]=moment({ years:temp[0], months:temp[1] - 1, date:temp[2]});		      		
			      		}
				}); */
				if($("#dept").combobox('getText').length>0)
				param["deptNames"]=$("#dept").combobox('getText');
				if($("#doerCodes").combobox('getText').length>0)
				param["doerNames"]=$("#doerCodes").combobox('getText');
				if($("#endDate").datebox('getText').length>0)
				{ var temp= $("#endDate").datebox('getText').toString().split('-');	
				 param["endDate"]=moment({ years:temp[0], months:temp[1] - 1, date:temp[2]});	}
				 
			},
			success:function(data){
				var data = JSON.parse(data);
				console.log(data);
				//$.messager.alert("提示",data.msg);
				if (data.code == "0"){
					
					$.messager.alert("提示",data.msg);
					popupWin.dialog('close');
					
					listPage.datagrid("reload");
				}
			}
		});
	} 
  export_button.linkbutton({ iconCls: 'icon-print', plain: true })
 .click(function () {
	  
	 	 var url="./api/"+modelname+"/toExcel/";
     excelExport(url,listPage); 
 });      
        
  function excelExport(url,grid){
 		var queryParams = grid.datagrid('options').queryParams;
 		var params = '?1=1';
 		$.each(queryParams, function(key, val){
 			params+='&'+key+'='+val;
 		}); 
 		var page = grid.datagrid('options').pageNumber; 
 		var rows= grid.datagrid('options').pageSize; 
 		params=params+"&page="+page+"&rows="+rows;
 		var fields = '&fields=';
 		var titles='&titles=';
 		$.each(grid.datagrid('options').columns[0], function(i, val){
 			if(val.field != 'opt'){
 				fields+=val.field+',';
 				titles+=val.title+',';
 			}
 		});  
 		params=params+fields+titles;
 		window.location.href = url+ encodeURI(params);
 	}
//弹出Excel数据导入窗口
  import_button.linkbutton({ iconCls: 'icon-save', plain: true })
  .click(function () {
  	importForm.form("reset");
  	importWin.dialog("open");
  });
//保存目标Excel到数据库，关闭Excel数据导入窗口，刷新datagrid
  importButton.linkbutton({ iconCls: 'icon-ok', plain: true})
  .click(function () {
  	if (importFile.filebox('getText').length == 0){
			$.messager.alert("提示","请选择要导入的文件！");
			return;
		}		 
  	//if (checkExcelFile("excel_file",pageName+"_import_file",pageName+"_import_popwin")){
			//$.messager.alert("提示","导入Excel！");
			importForm.ajaxSubmit({
		        type: "POST",
		        url:"api/fileController/uploadFile",//需要修改后台
		        dataType: "text",
		        success: function(data){
		        	
		        	var data = JSON.parse(data);
		            var str='<a href="'+data.path+data.finalName+'"  target="_blank" >'+data.origName+'</a>';
		            if(data.dispName!=null)
		            	 str='<a href="'+data.path+data.finalName+'"  target="_blank" >'+data.dispName+'</a>';
		            var values=$("#attachments").combobox('getValues');
		            values.push(str);
		        	$("#attachments").tagbox('setValues',values);
		        	//$("#attachments").text($("#attachments").text()+data.finalName);
		        	//$("#attachments").text('<a href="#" id="task_add" onclick="javascript:;">添加</a>');
		            //$.messager.alert("上传结果：",data.finalName);		            
		            importWin.dialog("close");
		            listPage.datagrid("reload");
		        }
		    });
			 
		//}
  });
  	$('#dept').combotree({
	    onChange: function(rec){
	    	if(rec!=undefined&&rec.toString()!="")
	    	   var url = 'api/user/getDeptsUsers?deptIds='+rec;
	            $('#doerCodes').combobox('clear');
	            $('#doerCodes').combobox('reload', url); 
	       }
	});
 
 	 Array.prototype.remove = function(val) { 
	  var index = this.indexOf(val); 
	  if (index > -1) { 
	  this.splice(index, 1); 
	  } 
	  };
 	 $("#attachments").tagbox({onRemoveTag:function(param){
	  if(state=="add")
         $.post("api/fileController/del",{'finalName':$(param).attr('href')}, function(data) {
    	 msg=JSON.parse(data).msg;
    	 $.messager.alert("系统提示",msg);
				});
	  }});
	function loadDetail(){
		state="edit";
		$("#buchongTd").css("display","");
		detailForm.form('reset');
		var row = listPage.datagrid('getSelected');
			//detailForm.form("load",row);
			$("#task_id").val(row.id);
			$("#title").textbox('setValue',row.title);
			$("#content").textbox('setValue',row.content);
			$("#remark").textbox('setValue',row.remark);
			$("#status").combobox('setValue', row.status);
			$("#endDate").datebox('setValue', row.endDate);
			if(row.deptIds!=null)
				{
				var values=row.deptIds.split(",");
				$("#dept").combotree('setValues',values);
				}
			else
			{
				$("#dept").combotree('setValues',[]);
			}
			if(row.doerCodes!=null)
			{
				var values=row.doerCodes.split(",");
				$("#doerCodes").combobox('setValues',values);
			}
			else
			{
				$("#doerCodes").combobox('setValues',[]);
			}
			//$("#all_pbc").combotree('setValue', row.jgId);
			$("#all_pbc").val(row.jgId);
			if(row.attachments!=null)
			{
				var values=row.attachments.split(",");
				$("#attachments").tagbox('setValues',values); 
			}
			else
				{
				$("#attachments").tagbox('setValues',[]); 
				}
			
			$("#title").textbox('textbox').attr('readonly',true);
			$("#content").textbox('textbox').attr('readonly',true);
		  /*  $("#attachments").tagbox('readonly',true);
			//$.parser.parse(detailForm);
			$(':input','#task_detail_form')  
			.attr('readonly','readonly');
			 */
			 popupWin.dialog({
				 onClose: function () {
			            $("#buchongTr").css("display", "none");
			        }
			    });
			 popupWin.dialog({title: "编辑工作任务"}).dialog('open');  				 
	};			

	$("#buchongBtn").linkbutton({ iconCls: 'icon-add', plain: true })
	.click(function () {
		$("#buchongTr").css("display","");
	    $('#buchong').next('span').find('textarea').focus();
	});
 
	this.REGX_HTML_ENCODE = /"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;  
	function encodeHtml(s) {  
	    return (typeof s != "string") ? s :  
	            s.replace(this.REGX_HTML_ENCODE,  
	                    function ($0) {  
	                        var c = $0.charCodeAt(0), r = ["&#"];  
	                        c = (c == 0x20) ? 0xA0 : c;  
	                        r.push(c);  
	                        r.push(";");  
	                        return r.join("");  
	                    });  
	}  	 
//将表单数据转为json
	function form2Json(id) {
	    var arr = $("#" + id).serializeArray()
	    var jsonStr = "";
	    jsonStr += '{';
	    for (var i = 0; i < arr.length; i++) {
	    	if(arr[i].value!="")
	        	jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",'
	    }
	    if(jsonStr.length>1)
	    	jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
	    jsonStr += '}'
	    var json = JSON.parse(jsonStr)
	    return json
	}

}();
</script>